from django.db import models
from django.utils.translation import gettext_lazy as _


# Create your models here.


class BucketSyncBaseInfo(models.Model):
    """备份配置信息表"""

    TYPE_CHOICES = (
        (0, '未同步'),
        (1, '同步中'),
        (2, '同步完成')
    )
    id = models.AutoField(primary_key=True, verbose_name=_('ID'))
    bash_url = models.CharField(verbose_name='服务地址', max_length=255)
    bucket_name = models.CharField(verbose_name='存储桶名称', max_length=255, default=None)
    local_dir = models.CharField(verbose_name='本地目录', max_length=255)
    remote_path = models.CharField(verbose_name='对象存储目录', max_length=255)
    bucket_token = models.CharField(verbose_name='存储桶token', max_length=255)
    sync_status = models.SmallIntegerField(verbose_name='同步状态', default=0, choices=TYPE_CHOICES)
    thread_num = models.IntegerField(verbose_name='并发量', default=3)
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    collection_name = models.CharField(max_length=50, default=None, blank=True, null=True,
                                       verbose_name='同步信息表前缀', help_text='z_sync_bucket_')
    inotify_name = models.CharField(max_length=50, default=None, blank=True, null=True,
                                    verbose_name='监控信息表前缀', help_text='z_inotify_bucket_')

    sync_time = models.DateTimeField(verbose_name='同步完成时间', blank=True, null=True, default=None)
    sync_status_enable = models.BooleanField(verbose_name='同步任务是否启动', default=False)
    inotify_status_enable = models.BooleanField(verbose_name='监控任务是否启动', default=False)
    dir_flag = models.BooleanField(verbose_name='目录遍历标记', default=True)

    class Meta:
        db_table = 'bucket_sync_base_info'
        ordering = ['-id']
        verbose_name = _('同步备份信息表')
        verbose_name_plural = verbose_name

    def get_bucket_table_name(self):
        """
        获得bucket对应的同步数据库表名
        :return: 表名
        """
        if not self.collection_name:
            name = f'z_sync_bucket_{self.id}'
            self.collection_name = name
            self.save(update_fields=['collection_name'])

        return f'{self.collection_name}'

    def get_inotify_table_name(self):
        """
        获得bucket对应的监控数据库表名
        :return: 表名
        """
        if not self.inotify_name:
            name = f'z_inotify_bucket_{self.id}'
            self.inotify_name = name
            self.save(update_fields=['inotify_name'])

        return f'{self.inotify_name}'

    def save(self, *args, **kwargs):
        if self.bash_url.endswith('/'):
            self.bash_url = self.bash_url.rstrip('/')

        if not self.local_dir.endswith('/'):
            self.local_dir = self.local_dir + '/'

        if not self.remote_path.endswith('/'):
            self.remote_path = self.remote_path + '/'

        self.thread_num = self.thread_num + 3

        super().save(*args, **kwargs)


class SyncFileBaseInfo(models.Model):
    """同步文件信息表"""
    id = models.AutoField(primary_key=True, verbose_name=_('ID'))
    bucket = models.ForeignKey(verbose_name='备份桶信息', to=BucketSyncBaseInfo, on_delete=models.SET_NULL, null=True)
    file_name = models.CharField(verbose_name='文件名称', max_length=255)
    file_path = models.TextField(verbose_name='全路径文件名')
    path_md5 = models.CharField(max_length=32, null=True, default=None, verbose_name='全路径MD5值')
    file_size = models.BigIntegerField(verbose_name='文件大小', default=0)
    remote_path = models.CharField(verbose_name='存储路径', max_length=1000, default=None)
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    mod_time = models.DateTimeField(verbose_name='修改时间', blank=True, null=True, default=None)
    sync_time = models.DateTimeField(verbose_name='同步时间', blank=True, null=True, default=None)

    class Meta:
        abstract = True
        app_label = 'metadata'
        ordering = ['-id']
        indexes = [models.Index(fields=('path_md5',))]
        verbose_name = _('同步文件信息表')
        verbose_name_plural = verbose_name


class InotifyFileBaseInfo(models.Model):
    """监控文件信息表"""

    TYPE_CHOICES = (
        (0, 'IN_CREATE'),
        (1, 'IN_DELETE'),
        (2, 'IN_CLOSE_WRITE'),
        (3, 'IN_MOVED_TO')
    )

    id = models.AutoField(primary_key=True, verbose_name=_('ID'))
    bucket = models.ForeignKey(verbose_name='备份桶信息', to=BucketSyncBaseInfo, on_delete=models.SET_NULL, null=True)
    file_name = models.CharField(verbose_name='文件名称', max_length=255)
    file_path = models.TextField(verbose_name='全路径文件名')
    path_md5 = models.CharField(max_length=32, null=True, default=None, verbose_name='全路径MD5值')
    file_size = models.BigIntegerField(verbose_name='文件大小', default=0)
    # remote_path = models.CharField(verbose_name='存储路径', max_length=1000, default=None)
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    mod_time = models.DateTimeField(verbose_name='修改时间', blank=True, null=True, default=None)
    inotify_status = models.SmallIntegerField(verbose_name='监控状态', default=0, choices=TYPE_CHOICES)

    class Meta:
        abstract = True
        app_label = 'metadata_inotify'
        ordering = ['-id']
        indexes = [models.Index(fields=('path_md5',))]
        verbose_name = _('监控文件信息表')
        verbose_name_plural = verbose_name


class SyncErrorLog(models.Model):
    """同步错误信息记录"""
    id = models.AutoField(primary_key=True, verbose_name=_('ID'))
    bucket = models.ForeignKey(verbose_name='备份配置信息', to=BucketSyncBaseInfo, on_delete=models.SET_NULL, null=True)
    # sync_file = models.ForeignKey(verbose_name='同步文件信息', to=SyncFileBaseInfo, on_delete=models.SET_NULL,
    #                               null=True)
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    err_msg = models.TextField(verbose_name='同步错误信息')

    class Meta:
        db_table = 'sync_error_log'
        ordering = ['-id']
        verbose_name = _('同步错误信息记录')
        verbose_name_plural = verbose_name


class AsyncTask(models.Model):
    """异步任务记录"""
    id = models.AutoField(primary_key=True, verbose_name=_('ID'))
    name = models.CharField(verbose_name='异步任务名称', max_length=255)

    class Meta:
        db_table = 'async_tesk_table'
        ordering = ['-id']
        verbose_name = _('异步任务记录')
        verbose_name_plural = verbose_name



# class StatisticsSyncFile(models.Model):
#     id = models.AutoField(primary_key=True, verbose_name=_('ID'))
#     bucket = models.ForeignKey(verbose_name='备份桶信息', to=BucketSyncBaseInfo, on_delete=models.SET_NULL)
#     file_num = models.BigIntegerField(verbose_name='文件数量', default=0)
#     create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
#
#     class Meta:
#         db_table = 'statistics_sync_file'
#         ordering = ['-id']
#         verbose_name = _('同步错误信息记录')
#         verbose_name_plural = verbose_name
